package cn.edu.swu.mhans.web.websocket;

import cn.edu.swu.mhans.common.util.ApplicationContextProvider;
import cn.edu.swu.mhans.game.service.GameService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * 游戏房间的webSocket连接
 *
 * @author ZhanJingbo
 * @version 1.0.0
 * Created on 2017/10/16
 */
@ServerEndpoint(value = "/webSocket/game/{roomId}/{userId}")
@Slf4j
@Component
public class RoomWebSocket {

    private GameService gameService;


    @OnOpen
    public void onConnectionOpen(@PathParam("roomId") String roomId, @PathParam("userId") Long userId, Session session) {
        getGameService().onConnectionOpen(roomId, userId, session);
    }

    @OnMessage
    public void onMessage(String jsonCommand, Session session) throws IOException {
        getGameService().onMessage(jsonCommand);
    }

    @OnClose
    public void onConnectionClose(@PathParam("roomId") String roomId, @PathParam("userId") Long userId) {
        getGameService().onConnectionClose(roomId, userId);
    }

    @OnError
    public void onConnectionError(Throwable error) {
        log.error("WebSocket连接错误", error);
        getGameService().onConnectionError(error);
    }

    GameService getGameService() {
        if (this.gameService == null) {
            this.gameService = ApplicationContextProvider.getBean(GameService.class);
        }
        return this.gameService;
    }
}
